/**
 * Created by ayu on 2017/6/28.
 */
const request = require ('request');
const logger = require ('../utils/logger/Logger');
const wechatAppConfig = require ('../../resources/WechatAppConfig');
let jsapiTicketDao = require ('../daos/JsapiTicketDao');
Date.prototype.format = function ( format )
{
    let o = {
        "M+": this.getMonth () + 1, //month
        "d+": this.getDate (), //day
        "H+": this.getHours (), //hour
        "m+": this.getMinutes (), //minute
        "s+": this.getSeconds (), //second
        "q+": Math.floor ((this.getMonth () + 3) / 3), //quarter
        "S" : this.getMilliseconds () //millisecond
    };
    if (/(y+)/.test (format))
    {
        format = format.replace (RegExp.$1,
            (this.getFullYear () + "").substr (4 - RegExp.$1.length));
    }
    for (let k in o)
        if (new RegExp ("(" + k + ")").test (format))
        {
            format = format.replace (RegExp.$1,
                RegExp.$1.length == 1 ? o[ k ] :
                    ("00" + o[ k ]).substr (("" + o[ k ]).length));
        }
    return format;
};

let jsapiTicket = '';
let getJsapiTicket = () => jsapiTicket;

let queryJsapiTicketFromWechat = accessToken =>
{
    let jsapiTicketUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi`;
    request ({
        url   : jsapiTicketUrl,
        method: 'GET'
    }, function ( err, response, _body )
    {
        if (err)
        {
            logger.warn ('从微信获取 JsapiTicket 失败：', err);
            return;
        }
        let body = JSON.parse (_body);
        jsapiTicket = body.ticket;
        let time = (new Date).format ('yyyy-MM-dd HH:mm:ss');
        jsapiTicketDao.saveJsapiTicket (body);
    });
};

let queryJsapiTicketFromDatabase = accessToken =>
{
    jsapiTicketDao.findJsapiTicket (function ( done )
    {
        let time = (new Date).format ('yyyy-MM-dd HH:mm:ss');
        if (done.isSuccess)
        {
            if (expired (done.result))
            {
                queryJsapiTicketFromWechat(accessToken);
            }
            else
            {
                jsapiTicket = done.result[0].ticket;
                console.log (`[${time}][JsapiTicket]  ${jsapiTicket}\n\n`);
            }
        }
        else
        {
            console.log (`[${time}] JsapiTicket 从数据库获取失败`);
        }
    });
};

let expired = accessTokenInfo =>
{
    if (accessTokenInfo.length === 0)
    {
        return true;
    }
    else
    {
        let timeRemaining = accessTokenInfo[ 0 ].expires_in - Date.now ();
        let time = (new Date).format ('yyyy-MM-dd HH:mm:ss');
        console.log (`\n[${time}][JsapiTicket] 过期还有${timeRemaining}毫秒`);
        return (accessTokenInfo.expires_in - Date.now ()) < 30000;
    }
};

let initJsapiTicket = accessToken =>
{
    queryJsapiTicketFromDatabase(accessToken);
};
module.exports = {
    initJsapiTicket           : initJsapiTicket,
    queryJsapiTicketFromWechat: queryJsapiTicketFromWechat,
};